package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.entity.domain.user.UserDO;
import com.qk.entity.dto.user.UserDTO;
import com.qk.entity.dto.user.UserLoginDTO;
import com.qk.entity.vo.user.UserLoginVO;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.qk.common.enums.ParamEnum.LOGIN_STATUS_ERROR;

/**
 * @author fantuan
 * @created 2025/10/7 18:14
 * @description
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    private static final Integer USER_STATUS_NORMAL = 1;
    private static final Integer USER_STATUS_UNNORMAL =0;

    @Override
    public PageResult<UserDO> list(UserDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<UserDO> result = userMapper.selectByPage(dto);
        result.forEach(userDO -> userDO.setPhone(DesensitizedUtil.mobilePhone(userDO.getPhone())));
        Page<UserDO> page = (Page<UserDO>) result;
        return PageResult.<UserDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void add(User user) {
        boolean hasNull = BeanUtil.hasNullField(user,"id","password","roleId","deptId","image","remark","createTime","updateTime");
        if(hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        String rawPassword = new StringBuilder(user.getUsername()).append("123").toString();
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        userMapper.insert(user);
    }

    @Override
    public void deleteById(List<Integer> ids) {
         boolean isNotEmpty = CollectionUtil.isNotEmpty(ids);
         if(!isNotEmpty){
             CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
         }
        userMapper.deleteById(ids);
    }

    @Override
    public UserDO getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public void update(User user) {
        boolean hasNull = BeanUtil.hasNullField(user,"id","password","roleId","deptId","image","remark","createTime","updateTime");
        if(hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public List<UserDO> selectAllUsers() {
        return userMapper.selectAllUsers();
    }

    @Override
    public List<UserDO> listByRole(String roleLabel) {
        return userMapper.listByRole(roleLabel);
    }

    @Override
    public List<UserDO> listByDept(Integer deptId) {
        return userMapper.listByDept(deptId);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {

        boolean hasNull = BeanUtil.hasNullField(dto);
        if(hasNull){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User dbUser = userMapper.selectByUsername(dto.getUsername());
        if(Objects.isNull(dbUser)){
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }
        if(ObjectUtil.equal(dbUser.getStatus(), USER_STATUS_UNNORMAL)){
            CommonException.throwCommonException(LOGIN_STATUS_ERROR);
        }
        String userPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        String encodePassword = dbUser.getPassword();
        boolean isChecked = ObjectUtil.equal(userPassword, encodePassword);
        if (!isChecked){
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }
        Role role = roleMapper.getRoleById(dbUser.getRoleId());
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",dbUser.getId());
        claims.put("username",dbUser.getUsername());
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtils.generateToken(claims))
                .build();

    }
}
